package com.woniuxy.interceptor;

import com.woniuxy.util.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@Component
public class AuthInterceptor implements HandlerInterceptor {

    //认证中心url
    private static final String AUTH_URL = "http://192.168.1.29:8061/login/loginUI";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //从Cookie中获取token
        Cookie tokenCookie = WebUtils.getCookie(request,"token");
        String tokenC = tokenCookie != null ? tokenCookie.getValue() : "";
        //从请求中获取token
        String tokenR = request.getParameter("token");
        //如果请求中包含token则优先使用请求中的token
        String token = tokenR != null ? tokenR : tokenC;

        //判断是否携带了token
        if (!StringUtils.isEmpty(token)) {
            //如果携带token，验证token
            boolean checkRes = JwtUtils.verifyToken(token);
            //如果token能被解析成功，则放行，保存cookie到客户端
            if (checkRes) {
                //此处添加Cookie只是添加了本服务的Cookie（并且不能设置其他服务的Cookie),单点登录并不需要添加此Cookie
//                tokenCookie = new Cookie("token", token);
//                response.addCookie(tokenCookie);
                return true;
            }else{
                //token解析失败则跳转到认证中心登录
                StringBuffer backUrl = request.getRequestURL();
                response.sendRedirect(AUTH_URL+"?backUrl="+ backUrl);
                return false;
            }
        }else {
            //没有携带token则携带自己的url去认证中心登录
            StringBuffer backUrl = request.getRequestURL();
            response.sendRedirect(AUTH_URL+"?backUrl="+ backUrl);
            return false;
        }
    }
}
